import os
import json
import numpy as np
import mindspore.dataset as ds
from mind3d.utils.provider import random_scale_point_cloud_class, shift_point_cloud_class

np.random.seed(4399)


class ShapeNetpartDataset:
    """
    A source dataset that reads, parses and augments the ShapeNet dataset.

    Args:
        root_path (str): The root directory of the ShapeNetpart dataset or inference pointcloud.
        split (str): The dataset split, supports "train", "val", or "infer". Default: "train".
        num_points(int): The number of points. Default: 1024.
        normal_channel (bool): Whether to use rgb information. Default: False.
        class_choice (str): Choose some classes to train. Default: None.

    Raises:
        ValueError: If `split` is not 'train', 'val' or 'test'.

    About ShapeNet dataset:
    This dataset provides part segmentation to a subset of ShapeNetCore models, containing ~16K models from 16 shape
    categories. The number of parts for each category varies from 2 to 6 and there are a total number of 50 parts.

    You can unzip the dataset files into this directory structure and read them by MindSpore Vision's API.

    .. code-block::

        ./shapenetcore_partanno_segmentation_benchmark_v0_normal/
        ├── 02691156
        │   ├── 1a04e3eab45ca15dd86060f189eb133.txt
        │   ├── 1a32f10b20170883663e90eaf6b4ca52.txt
        │   └── ....
        ├── 02773838
        ├── 02954340
        ├── ....
        ├── train_test_split
        └── synsetoffset2category.txt

    Citation:

    .. code-block::

        @article{Yi16,
        Author = {Li Yi and Vladimir G. Kim and Duygu Ceylan and I-Chao Shen and Mengyan Yan and Hao Su and Cewu Lu and
        Qixing Huang and Alla Sheffer and Leonidas Guibas},
        Journal = {SIGGRAPH Asia},
        Title = {A Scalable Active Framework for Region Annotation in 3D Shape Collections},
        Year = {2016}
        }
    """
    def __init__(self, root_path, split='train', num_points=1024, normal_channel=False, class_choice=None):
        self.path = root_path
        self.num_points = num_points
        self.normal_channel = normal_channel
        self.catfile = os.path.join(self.path, 'synsetoffset2category.txt')
        self.cat = {}

        with open(self.catfile, 'r') as f:
            for line in f:
                ls = line.strip().split()
                self.cat[ls[0]] = ls[1]
        self.cat = {k: v for k, v in self.cat.items()}
        self.classes_original = dict(zip(self.cat, range(len(self.cat))))

        if not class_choice is None:
            self.cat = {k: v for k, v in self.cat.items() if k in class_choice}

        self.meta = {}
        with open(os.path.join(self.path, 'train_test_split', 'shuffled_train_file_list.json'), 'r') as f:
            train_ids = set([str(d.split('/')[2]) for d in json.load(f)])
        with open(os.path.join(self.path, 'train_test_split', 'shuffled_val_file_list.json'), 'r') as f:
            val_ids = set([str(d.split('/')[2]) for d in json.load(f)])
        with open(os.path.join(self.path, 'train_test_split', 'shuffled_test_file_list.json'), 'r') as f:
            test_ids = set([str(d.split('/')[2]) for d in json.load(f)])
        for item in self.cat:
            self.meta[item] = []
            dir_point = os.path.join(self.path, self.cat[item])
            fns = sorted(os.listdir(dir_point))
            if split == 'trainval':
                fns = [fn for fn in fns if ((fn[0:-4] in train_ids) or (fn[0:-4] in val_ids))]
            elif split == 'train':
                fns = [fn for fn in fns if fn[0:-4] in train_ids]
            elif split == 'val':
                fns = [fn for fn in fns if fn[0:-4] in val_ids]
            elif split == 'test':
                fns = [fn for fn in fns if fn[0:-4] in test_ids]
            else:
                print('Unknown split: %s. Existing..' % split)
                exit(1)

            for fn in fns:
                token = (os.path.splitext(os.path.basename(fn))[0])
                self.meta[item].append(os.path.join(dir_point, token + '.txt'))

        self.datapath = []
        for item in self.cat:
            for fn in self.meta[item]:
                self.datapath.append((item, fn))

        self.classes = {}
        for i in self.cat.keys():
            self.classes[i] = self.classes_original[i]

        self.seg_classes = {'Earphone': [16, 17, 18], 'Motorbike': [30, 31, 32, 33, 34, 35], 'Rocket': [41, 42, 43],
                            'Car': [8, 9, 10, 11], 'Laptop': [28, 29], 'Cap': [6, 7], 'Skateboard': [44, 45, 46],
                            'Mug': [36, 37], 'Guitar': [19, 20, 21], 'Bag': [4, 5], 'Lamp': [24, 25, 26, 27],
                            'Table': [47, 48, 49], 'Airplane': [0, 1, 2, 3], 'Pistol': [38, 39, 40],
                            'Chair': [12, 13, 14, 15], 'Knife': [22, 23]}

        self.cache = {}
        self.cache_size = 20000

    def __getitem__(self, index):
        if index in self.cache:
            point_set, cls, seg = self.cache[index]
        else:
            fn = self.datapath[index]
            cat = self.datapath[index][0]
            cls = self.classes[cat]
            cls = np.array([cls]).astype(np.int32)
            data = np.loadtxt(fn[1]).astype(np.float32)
            if not self.normal_channel:
                point_set = data[:, 0:3]
            else:
                point_set = data[:, 0:6]
            seg = data[:, -1].astype(np.int32)
            if len(self.cache) < self.cache_size:
                self.cache[index] = (point_set, cls, seg)
        point_set[:, 0:3] = self._pc_normalize(point_set[:, 0:3])

        if len(seg) >= self.num_points:
            point_set = point_set[:self.num_points, :]
            seg = seg[:self.num_points]
        else:
            numbers = self.num_points - len(seg)
            zeros = np.array(point_set[0, :]).reshape(1, -1)
            zeros = zeros.repeat(numbers, axis=0)
            point_set = point_set[:self.num_points, :]
            seg_zeros = np.array(seg[0]).repeat(numbers, axis=0)
            seg = seg[:self.num_points]
            point_set = np.concatenate((point_set, zeros), axis=0)
            seg = np.concatenate((seg, seg_zeros), axis=0)

        return point_set, cls, seg

    def __len__(self):
        return len(self.datapath)

    def _pc_normalize(self, data):
        centroid = np.mean(data, axis=0)
        data = data - centroid
        m = np.max(np.sqrt(np.sum(data ** 2, axis=1)))
        data /= m
        return data

def create_shapenet_dataset(args_opt, split):

    if split == "train":
        is_shuffe = True
    num_worker = args_opt.TrainSeg.num_work
    batch_size = args_opt.TrainSeg.batch_size

    dataset_generator = ShapeNetpartDataset(root_path=args_opt.TrainSeg.data_path, num_points = args_opt.TrainSeg.num_points, split=split, 
                                        normal_channel= True)
    dataset = ds.GeneratorDataset(dataset_generator, ["point_set", "cls", "seg"],
                                      shuffle=True, num_parallel_workers=num_worker)
    if split == 'train':
        trans = [random_scale_point_cloud_class(), shift_point_cloud_class()]
        dataset = dataset.map(operations=trans,
                              input_columns="point_set",
                              num_parallel_workers=num_worker)

    dataset = dataset.batch(batch_size=10, drop_remainder=True)    

    return dataset